<template>
	<view class="home-container">
		<!-- 顶部状态栏 -->
		<view class="status-bar">
			<view class="hospital-info">
				<view class="hospital-name">{{ currentHospital.name }}</view>
				<view class="level-selector" @click="showLevelPicker">
					{{ currentLevel }} <text class="iconfont icon-arrow-down"></text>
				</view>
			</view>
			<view class="network-status" :class="{ 'offline': !networkStatus }">
				<text class="iconfont" :class="networkStatus ? 'icon-wifi' : 'icon-offline'"></text>
			</view>
		</view>

		<!-- KPI 卡片区域 -->
		<view class="kpi-section">
			<view class="section-title">今日概览</view>
			<view class="kpi-grid">
				<view class="kpi-card" v-for="(kpi, index) in kpiData" :key="index" @click="navigateToDetail(kpi.type)">
					<view class="kpi-icon" :style="{ backgroundColor: kpi.color }">
						<text class="iconfont" :class="kpi.icon"></text>
					</view>
					<view class="kpi-content">
						<view class="kpi-value">{{ kpi.value }}</view>
						<view class="kpi-label">{{ kpi.label }}</view>
						<view class="kpi-change" :class="kpi.trend">
							<text class="iconfont" :class="kpi.trend === 'up' ? 'icon-trend-up' : 'icon-trend-down'"></text>
							{{ kpi.change }}
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 实时数据图表 -->
		<view class="charts-section">
			<view class="section-header">
				<view class="section-title">实时监控</view>
				<view class="time-label">{{ currentTime }}</view>
				<view class="more-btn" @click="navigateToCharts">
					<text class="iconfont icon-more"></text>
				</view>
			</view>
			
			<!-- 人流密度图表 -->
			<view class="chart-card">
				<view class="chart-header">
					<view class="chart-title">人流密度趋势</view>
					<view class="chart-unit">人/m²</view>
				</view>
				<canvas 
					class="ec-canvas" 
					canvas-id="densityChart"
					id="densityChart"
					@touchstart="onChartTouchStart"
					@touchmove="onChartTouchMove"
					@touchend="onChartTouchEnd"
				></canvas>
			</view>
			
			<!-- 等待时间图表 -->
			<view class="chart-card">
				<view class="chart-header">
					<view class="chart-title">平均等待时间</view>
					<view class="chart-unit">分钟</view>
				</view>
				<canvas 
					class="ec-canvas" 
					canvas-id="waitTimeChart"
					id="waitTimeChart"
					@touchstart="onChartTouchStart"
					@touchmove="onChartTouchMove"
					@touchend="onChartTouchEnd"
				></canvas>
			</view>
		</view>

		<!-- 告警快览 -->
		<view class="alerts-section">
			<view class="section-header">
				<view class="section-title">
					告警中心
					<view class="alert-badge" v-if="alertsCount > 0">{{ alertsCount }}</view>
				</view>
				<view class="more-btn" @click="navigateToAlerts">
					<text class="iconfont icon-more"></text>
				</view>
			</view>
			<view class="alerts-list" v-if="alertsTopN.length > 0">
				<view class="alert-item" v-for="alert in alertsTopN" :key="alert.id" @click="navigateToAlertDetail(alert.id)">
					<view class="alert-icon" :class="'severity-' + alert.severity">
						<text class="iconfont" :class="getAlertIcon(alert.type)"></text>
					</view>
					<view class="alert-content">
						<view class="alert-title">{{ alert.title }}</view>
						<view class="alert-location">{{ alert.location }}</view>
						<view class="alert-time">{{ formatTime(alert.startedAt) }}</view>
					</view>
					<view class="alert-status" :class="alert.status">
						{{ getStatusText(alert.status) }}
					</view>
				</view>
			</view>
			<view class="empty-state" v-else>
				<text class="iconfont icon-check-circle"></text>
				<text class="empty-text">暂无告警</text>
			</view>
		</view>

		<!-- 快捷服务 -->
		<view class="quick-services">
			<view class="section-title">快捷服务</view>
			<view class="services-grid">
				<view class="service-item" v-for="service in quickServices" :key="service.type" @click="handleQuickService(service.type)">
					<view class="service-icon" :style="{ backgroundColor: service.color }">
						<text class="iconfont" :class="service.icon"></text>
					</view>
					<view class="service-label">{{ service.label }}</view>
					<view class="service-desc">{{ service.desc }}</view>
				</view>
			</view>
		</view>
		
		<!-- 今日就医 -->
		<view class="today-medical" v-if="todayAppointments.length > 0">
			<view class="section-title">今日就医</view>
			<view class="appointments-list">
				<view class="appointment-card" v-for="appointment in todayAppointments" :key="appointment.id" @click="viewAppointmentDetail(appointment.id)">
					<view class="appointment-time">
						<view class="time-slot">{{ appointment.timeSlot }}</view>
						<view class="status-badge" :class="appointment.status">{{ getAppointmentStatus(appointment.status) }}</view>
					</view>
					<view class="appointment-info">
						<view class="doctor-name">{{ appointment.doctorName }}</view>
						<view class="department">{{ appointment.departmentName }}</view>
						<view class="location">{{ appointment.location }}</view>
					</view>
					<view class="appointment-actions">
						<view class="queue-info" v-if="appointment.queueInfo">
							<text class="queue-number">排队{{ appointment.queueInfo.position }}人</text>
							<text class="wait-time">约{{ appointment.queueInfo.waitTime }}分钟</text>
						</view>
						<text class="iconfont icon-arrow-right"></text>
					</view>
				</view>
			</view>
		</view>

		<!-- 楼层选择器 -->
		<uni-popup ref="levelPopup" type="bottom">
			<view class="level-picker">
				<view class="picker-header">
					<view class="picker-title">选择楼层</view>
					<view class="picker-close" @click="closeLevelPicker">
						<text class="iconfont icon-close"></text>
					</view>
				</view>
				<view class="picker-content">
					<view class="level-item" v-for="level in availableLevels" :key="level.id" @click="selectLevel(level)" :class="{ 'active': level.id === currentLevel }">
						<view class="level-name">{{ level.name }}</view>
						<view class="level-desc">{{ level.description }}</view>
						<text class="iconfont icon-check" v-if="level.id === currentLevel"></text>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { mapState, mapActions } from 'vuex'

export default {
	name: 'HomePage',
	data() {
		return {
			currentTime: '',
			timeTimer: null,
			refreshTimer: null,
			densityLegend: [
				{ color: '#4CAF50', label: '低' },
				{ color: '#FF9800', label: '中' },
				{ color: '#F44336', label: '高' }
			]
		}
	},
	computed: {
		...mapState('app', ['currentHospital', 'currentLevel', 'networkStatus']),
		...mapState('home', ['kpiData', 'miniHeatmap', 'alertsTopN', 'alertsCount', 'availableLevels']),
		quickActions() {
			return [
				{
					type: 'simulation',
					label: '启动仿真',
					icon: 'icon-play',
					color: '#007AFF'
				},
				{
					type: 'emergency',
					label: '应急疏散',
					icon: 'icon-emergency',
					color: '#FF3B30'
				},
				{
					type: 'route',
					label: '路径规划',
					icon: 'icon-route',
					color: '#34C759'
				},
				{
					type: 'report',
					label: '现场上报',
					icon: 'icon-camera',
					color: '#FF9500'
				}
			]
		}
	},
	onLoad() {
		this.initPage()
	},
	onShow() {
		this.refreshData()
		this.startAutoRefresh()
	},
	onHide() {
		this.stopAutoRefresh()
	},
	onUnload() {
		this.stopAutoRefresh()
	},
	onPullDownRefresh() {
		this.refreshData().finally(() => {
			uni.stopPullDownRefresh()
		})
	},
	methods: {
		...mapActions('home', ['loadKpiData', 'loadMiniHeatmap', 'loadAlerts']),
		...mapActions('app', ['setCurrentLevel']),
		
		async initPage() {
			await this.checkLoginStatus()
			this.updateCurrentTime()
			this.startTimer()
			await this.refreshData()
		},
		
		async checkLoginStatus() {
			const token = uni.getStorageSync('token')
			if (!token) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
				return
			}
		},
		
		async refreshData() {
			try {
				await Promise.all([
					this.loadKpiData(),
					this.loadMiniHeatmap(),
					this.loadAlerts()
				])
			} catch (error) {
				console.error('数据加载失败:', error)
				uni.showToast({
					title: '数据加载失败',
					icon: 'none'
				})
			}
		},
		
		startTimer() {
			this.timeTimer = setInterval(() => {
				this.updateCurrentTime()
			}, 1000)
		},
		
		updateCurrentTime() {
			const now = new Date()
			this.currentTime = now.toLocaleTimeString('zh-CN', {
				hour: '2-digit',
				minute: '2-digit'
			})
		},
		
		startAutoRefresh() {
			this.refreshTimer = setInterval(() => {
				this.refreshData()
			}, 30000) // 30秒自动刷新
		},
		
		stopAutoRefresh() {
			if (this.timeTimer) {
				clearInterval(this.timeTimer)
				this.timeTimer = null
			}
			if (this.refreshTimer) {
				clearInterval(this.refreshTimer)
				this.refreshTimer = null
			}
		},
		
		showLevelPicker() {
			this.$refs.levelPopup.open()
		},
		
		closeLevelPicker() {
			this.$refs.levelPopup.close()
		},
		
		async selectLevel(level) {
			await this.setCurrentLevel(level.id)
			this.closeLevelPicker()
			this.refreshData()
		},
		
		navigateToDetail(type) {
			const routes = {
				'avgWait': '/pages/heatmap/index?type=wait',
				'maxDensity': '/pages/heatmap/index?type=density',
				'conflictRate': '/pages/alerts/index?type=conflict',
				'bottleneckCount': '/pages/heatmap/index?type=bottleneck'
			}
			const url = routes[type] || '/pages/heatmap/index'
			uni.navigateTo({ url })
		},
		
		navigateToHeatmap() {
			uni.navigateTo({
				url: '/pages/heatmap/index'
			})
		},
		
		navigateToViewer() {
			uni.navigateTo({
				url: '/pages/viewer/index'
			})
		},
		
		navigateToAlerts() {
			uni.switchTab({
				url: '/pages/alerts/index'
			})
		},
		
		navigateToAlertDetail(alertId) {
			uni.navigateTo({
				url: `/pages/alerts/detail?id=${alertId}`
			})
		},
		
		handleQuickAction(type) {
			const actions = {
				'simulation': () => {
					uni.switchTab({
						url: '/pages/simulation/index'
					})
				},
				'emergency': () => {
					uni.navigateTo({
						url: '/pages/route/emergency'
					})
				},
				'route': () => {
					uni.navigateTo({
						url: '/pages/route/plan'
					})
				},
				'report': () => {
					uni.navigateTo({
						url: '/pages/report/sample'
					})
				}
			}
			
			const action = actions[type]
			if (action) {
				action()
			}
		},
		
		getAlertIcon(type) {
			const icons = {
				'crowding': 'icon-people',
				'conflict': 'icon-warning',
				'overload': 'icon-alert',
				'blockage': 'icon-block'
			}
			return icons[type] || 'icon-alert'
		},
		
		getStatusText(status) {
			const statusMap = {
				'new': '新告警',
				'processing': '处理中',
				'resolved': '已解决'
			}
			return statusMap[status] || status
		},
		
		formatTime(timestamp) {
			const date = new Date(timestamp)
			const now = new Date()
			const diff = now.getTime() - date.getTime()
			
			if (diff < 60000) {
				return '刚刚'
			} else if (diff < 3600000) {
				return Math.floor(diff / 60000) + '分钟前'
			} else if (diff < 86400000) {
				return Math.floor(diff / 3600000) + '小时前'
			} else {
				return date.toLocaleDateString('zh-CN')
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.home-container {
	padding: 0 24rpx;
	background-color: #f8f9fa;
	min-height: 100vh;
}

.status-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 0;
	
	.hospital-info {
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.hospital-name {
			font-size: 32rpx;
			font-weight: 600;
			color: #1a1a1a;
		}
		
		.level-selector {
			display: flex;
			align-items: center;
			gap: 8rpx;
			padding: 8rpx 16rpx;
			background-color: #007AFF;
			color: white;
			font-size: 24rpx;
			border-radius: 16rpx;
		}
	}
	
	.network-status {
		color: #34C759;
		font-size: 32rpx;
		
		&.offline {
			color: #FF3B30;
		}
	}
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-bottom: 24rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
	
	.time-label {
		font-size: 24rpx;
		color: #666;
	}
	
	.more-btn {
		color: #007AFF;
		font-size: 32rpx;
	}
}

.kpi-section {
	margin-bottom: 48rpx;
	
	.kpi-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 24rpx;
	}
	
	.kpi-card {
		background: white;
		border-radius: 16rpx;
		padding: 32rpx;
		display: flex;
		align-items: center;
		gap: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		
		.kpi-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 16rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: white;
			font-size: 36rpx;
		}
		
		.kpi-content {
			flex: 1;
			
			.kpi-value {
				font-size: 40rpx;
				font-weight: 700;
				color: #1a1a1a;
				line-height: 1.2;
			}
			
			.kpi-label {
				font-size: 24rpx;
				color: #666;
				margin: 8rpx 0;
			}
			
			.kpi-change {
				display: flex;
				align-items: center;
				gap: 8rpx;
				font-size: 20rpx;
				
				&.up {
					color: #FF3B30;
				}
				
				&.down {
					color: #34C759;
				}
			}
		}
	}
}

.heatmap-section {
	margin-bottom: 48rpx;
	
	.heatmap-container {
		position: relative;
		height: 300rpx;
		border-radius: 16rpx;
		overflow: hidden;
		background: white;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		
		.heatmap-thumbnail {
			width: 100%;
			height: 100%;
		}
		
		.heatmap-overlay {
			position: absolute;
			bottom: 24rpx;
			right: 24rpx;
			
			.density-legend {
				display: flex;
				gap: 16rpx;
				
				.legend-item {
					display: flex;
					align-items: center;
					gap: 8rpx;
					padding: 8rpx 12rpx;
					background: rgba(255, 255, 255, 0.9);
					border-radius: 8rpx;
					
					.legend-color {
						width: 16rpx;
						height: 16rpx;
						border-radius: 50%;
					}
					
					.legend-text {
						font-size: 20rpx;
						color: #333;
					}
				}
			}
		}
	}
}

.alerts-section {
	margin-bottom: 48rpx;
	
	.section-title {
		display: flex;
		align-items: center;
		gap: 16rpx;
		
		.alert-badge {
			background: #FF3B30;
			color: white;
			font-size: 20rpx;
			padding: 4rpx 12rpx;
			border-radius: 12rpx;
			min-width: 32rpx;
			text-align: center;
		}
	}
	
	.alerts-list {
		background: white;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	.alert-item {
		display: flex;
		align-items: center;
		gap: 24rpx;
		padding: 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
		
		&:last-child {
			border-bottom: none;
		}
		
		.alert-icon {
			width: 64rpx;
			height: 64rpx;
			border-radius: 12rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: white;
			font-size: 28rpx;
			
			&.severity-high {
				background: #FF3B30;
			}
			
			&.severity-medium {
				background: #FF9500;
			}
			
			&.severity-low {
				background: #34C759;
			}
		}
		
		.alert-content {
			flex: 1;
			
			.alert-title {
				font-size: 28rpx;
				color: #1a1a1a;
				font-weight: 500;
				margin-bottom: 8rpx;
			}
			
			.alert-location {
				font-size: 24rpx;
				color: #666;
				margin-bottom: 4rpx;
			}
			
			.alert-time {
				font-size: 20rpx;
				color: #999;
			}
		}
		
		.alert-status {
			font-size: 20rpx;
			padding: 8rpx 16rpx;
			border-radius: 12rpx;
			
			&.new {
				background: #FF3B30;
				color: white;
			}
			
			&.processing {
				background: #FF9500;
				color: white;
			}
			
			&.resolved {
				background: #34C759;
				color: white;
			}
		}
	}
	
	.empty-state {
		background: white;
		border-radius: 16rpx;
		padding: 80rpx 32rpx;
		text-align: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		
		.iconfont {
			font-size: 96rpx;
			color: #34C759;
			margin-bottom: 24rpx;
		}
		
		.empty-text {
			font-size: 28rpx;
			color: #666;
		}
	}
}

.quick-actions {
	margin-bottom: 48rpx;
	
	.actions-grid {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr 1fr;
		gap: 24rpx;
	}
	
	.action-item {
		background: white;
		border-radius: 16rpx;
		padding: 32rpx 16rpx;
		text-align: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		
		.action-icon {
			width: 80rpx;
			height: 80rpx;
			border-radius: 16rpx;
			margin: 0 auto 16rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: white;
			font-size: 36rpx;
		}
		
		.action-label {
			font-size: 24rpx;
			color: #1a1a1a;
			line-height: 1.4;
		}
	}
}

.level-picker {
	background: white;
	border-radius: 24rpx 24rpx 0 0;
	
	.picker-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
		
		.picker-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #1a1a1a;
		}
		
		.picker-close {
			color: #666;
			font-size: 32rpx;
		}
	}
	
	.picker-content {
		max-height: 600rpx;
		overflow-y: auto;
	}
	
	.level-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
		
		&:last-child {
			border-bottom: none;
		}
		
		&.active {
			background: #f0f9ff;
			
			.level-name {
				color: #007AFF;
			}
		}
		
		.level-name {
			font-size: 28rpx;
			color: #1a1a1a;
			font-weight: 500;
		}
		
		.level-desc {
			font-size: 24rpx;
			color: #666;
			margin-top: 8rpx;
		}
		
		.iconfont {
			color: #007AFF;
			font-size: 32rpx;
		}
	}
}
</style> 